<?php
/**
 *
 * Ajax评论
 *
 * @version        $Id: feedback_ajax.php 1 15:38 2010年7月8日Z tianya $
 * @package        DedeCMS.Site
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__).'/../include/common.inc.php');
require_once(DEDEINC.'/channelunit.func.php');
AjaxHead();

if($cfg_feedback_forbid=='Y') exit('系统已经禁止评论功能！');

$aid = intval($aid);
if(empty($aid)) exit('没指定评论文档的ID，不能进行操作！');

include_once(DEDEINC.'/memberlogin.class.php');
$cfg_ml = new MemberLogin();

if(empty($dopost)) $dopost = '';
$page = empty($page) || $page<1 ? 1 : intval($page);
$pagesize = 10;

/*----------------------
获得指定页的评论内容
function getlist(){ }
----------------------*/
if($dopost=='getlist')
{
    $totalcount = GetList($page);
    GetPageList($pagesize, $totalcount);
    exit();
}
/*----------------------
获得指定页的评论内容的条数
function getlist(){ }
----------------------*/
if($dopost=='nuus')
{
    $row = $dsql->GetOne("SELECT COUNT(*) FROM `#@__feedback` WHERE `aid`='$aid'");
    echo $row['COUNT(*)'];
    exit();
}
/*----------------------
发送评论
function send(){ }
----------------------*/
else if($dopost=='send')
{
    require_once(DEDEINC.'/charset.func.php');
    
    $arcRow = GetOneArchive($aid);
    if(empty($arcRow['aid']))
    {
        echo '<font color="red">无法查看未知文档的评论!</font>';
        exit();
    }
    if(isset($arcRow['notpost']) && $arcRow['notpost']==1)
    {
        echo '<font color="red">这篇文档禁止评论!</font>';
        exit();
    }
    
    if( $cfg_soft_lang != 'utf8' )
    {
        $msg = UnicodeUrl2Gbk($msg);
        if(!empty($username)) $username = UnicodeUrl2Gbk($username);
    }
    //词汇过滤检查
    if( $cfg_notallowstr != '' )
    {
        if(preg_match("#".$cfg_notallowstr."#i", $msg))
        {
            echo "<font color='red'>评论内容含有禁用词汇！</font>";
            exit();
        }
    }
    if( $cfg_replacestr != '' )
    {
        $msg = preg_replace("#".$cfg_replacestr."#i", '***', $msg);
    }
    if( empty($msg) )
    {
        echo "<font color='red'>评论内容可能不合法或为空！</font>";
        exit();
    }
	if($cfg_feedback_guest == 'N' && $cfg_ml->M_ID < 1)
	{
		echo "<font color='red'>管理员禁用了游客评论！<a href='{$cfg_cmspath}/user/login.php'>点击登录</a></font>";
		exit();
	}
    //检查用户
    $username = empty($username) ? '游客' : $username;
    if(empty($notuser)) $notuser = 0;
    if($notuser==1)
    {
        $username = $cfg_ml->M_ID > 0 ? '匿名' : '游客';
    }
    else if($cfg_ml->M_ID > 0)
    {
        $username = $cfg_ml->M_LoginID;
    }
    else if($username!='' && $pwd!='')
    {
        $rs = $cfg_ml->CheckUser($username, $pwd);
        if($rs==1)
        {
            $dsql->ExecuteNoneQuery("Update `#@__member` set logintime='".time()."',loginip='".GetIP()."' where mid='{$cfg_ml->M_ID}'; ");
        }
        $cfg_ml = new MemberLogin();
    }
    
    //检查评论间隔时间
    $ip = GetIP();
    $dtime = time();
    if(!empty($cfg_feedback_time))
    {
        //检查最后发表评论时间，如果未登陆判断当前IP最后评论时间
        $where = ($cfg_ml->M_ID > 0 ? "WHERE `mid` = '$cfg_ml->M_ID' " : "WHERE `ip` = '$ip' ");
        $row = $dsql->GetOne("SELECT dtime FROM `#@__feedback` $where ORDER BY `id` DESC ");
        if(is_array($row) && $dtime - $row['dtime'] < $cfg_feedback_time)
        {
            ResetVdValue();
            echo '<font color="red">管理员设置了评论间隔时间，请稍等休息一下！</font>';
            exit();
        }
    }
    $face = 1;
    extract($arcRow, EXTR_SKIP);
    $msg = cn_substrR(TrimMsg($msg), 500);
    $username = cn_substrR(HtmlReplace($username,2), 20);
    //保存评论内容
    if(!empty($fid))
    {
        $row = $dsql->GetOne("SELECT username,msg from `#@__feedback` WHERE id ='$fid' ");
        $qmsg = '{quote}{content}'.$row['msg'].'{/content}{title}'.$row['username'].' 的原帖：{/title}{/quote}';
        $msg = addslashes($qmsg).$msg;
    }
    $ischeck = ($cfg_feedbackcheck=='Y' ? 0 : 1);
    $arctitle = addslashes(RemoveXSS($title));
    $typeid = intval($typeid);
    $feedbacktype = preg_replace("#[^0-9a-z]#i", "", $feedbacktype);
	$face = mt_rand(1, 50);
	    $inquery = "INSERT INTO `#@__feedback`(`aid`,`typeid`,`username`,`arctitle`,`ip`,`ischeck`,`dtime`,`mid`,`ftype`,`face`,`msg`)
                   VALUES ('$aid','$typeid','$username','$arctitle','$ip','$ischeck','$dtime','{$cfg_ml->M_ID}','$feedbacktype','$face','$msg'); ";
    $rs = $dsql->ExecuteNoneQuery($inquery);
    if( !$rs )
    {
            echo "<font color='red'>发表评论出错了！</font>";
            //echo $dslq->GetError();
            exit();
    }
    $newid = $dsql->GetLastID();

    //给用户增加积分
    if($cfg_ml->M_ID > 0)
    {
        $dsql->ExecuteNoneQuery("UPDATE `#@__member` set scores=scores+{$cfg_sendfb_scores} WHERE mid='{$cfg_ml->M_ID}' ");
        $row = $dsql->GetOne("SELECT COUNT(*) AS nums FROM `#@__feedback` WHERE `mid`='".$cfg_ml->M_ID."'");
    }
    $_SESSION['sedtime'] = time();
    if($ischeck==0)
    {
        echo '<font color="red">成功发表评论，但需审核后才会显示你的评论!</font>';
        exit();
    }
    else
    {
        $spaceurl = '#';
        if($cfg_ml->M_ID > 0) $spaceurl = "{$cfg_memberurl}/index.php?uid=".urlencode($cfg_ml->M_LoginID);
        $id = $newid;
        $msg = stripslashes($msg);
        $msg = str_replace('<', '&lt;', $msg);
        $msg = str_replace('>', '&gt;', $msg);
		helper('smiley');
        $msg = RemoveXSS(Quote_replace(parseSmileys($msg, $cfg_cmspath.'/images/smiley')));
        if($feedbacktype=='bad') $bgimg = 'cmt-bad.gif';
        else if($feedbacktype=='good') $bgimg = 'cmt-good.gif';
        else $bgimg = 'cmt-neu.gif';
        global $dsql, $aid, $pagesize, $cfg_templeturl;
        if($cfg_ml->M_ID==""){
             $mface=$cfg_cmspath."/user/templets/images/dfboy.png";
        } else {
          $row = $dsql->GetOne("SELECT face,sex FROM `#@__member` WHERE mid={$cfg_ml->M_ID} ");
            if(empty($row['face']))
            {
             // if($row['sex']=="女") $mface=$cfg_cmspath."/user/templets/images/dfgirl.png";
             $mface=$cfg_cmsurl."/images/noface.gif";
            }else{
				$mface=	$row['face'];
			}
        }
?>

<li class="comment odd alt thread-odd thread-alt depth-1">
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
    <div class="comment-author vcard">
    <a href='<?php echo $spaceurl; ?>' class='plpic' target="_blank"><img src='<?php echo $mface;?>'  height='44' width='44'/></a>
    </div>
    <div class="comment-meta">
    <span class="author"><cite><a href="<?php echo $spaceurl; ?>" target="_blank"><?php echo $username; ?></a></cite></span>
    <span class="date"> <?php echo GetDateMk($dtime); ?> </span>
     </div> 
    <div class="comment-main">
    <p><?php echo ubb($msg); ?></p>
     </div> 
     <!-- <div class="comment-floor">*<span style="font-size:12px;">F</span></div> -->
 </div>
</li>

<?php
    }
    exit();
}

/**
 *  读取列表内容
 *
 * @param     int  $page  页码
 * @return    string
 */
function GetList($page=1)
{
    global $dsql, $aid, $pagesize, $cfg_templeturl,$cfg_cmspath;
    $querystring = "SELECT fb.*,mb.userid,mb.face as mface,mb.spacesta,mb.scores FROM `#@__feedback` fb
                 LEFT JOIN `#@__member` mb on mb.mid = fb.mid WHERE fb.aid='$aid' AND fb.ischeck='1' ORDER BY fb.id DESC";
    $row = $dsql->GetOne("SELECT COUNT(*) AS dd FROM `#@__feedback` WHERE aid='$aid' AND ischeck='1' ");
    $totalcount = (empty($row['dd']) ? 0 : $row['dd']);
    $startNum = $pagesize * ($page-1);
    if($startNum > $totalcount)
    {
        echo "参数错误！";
       return $totalcount;
    }
    $dsql->Execute('fb', $querystring." LIMIT $startNum, $pagesize ");
$i = '0';
    while($fields = $dsql->GetArray('fb'))
    {
		$i++; 
        if($fields['userweb']!='') $userweb = $fields['userweb'];
        else $userweb = '#';
		if(empty($fields['mface']))
        {
            if($fields['sex']=="女") $fields['mface']=$cfg_cmsurl."/images/noface.gif";
            else $fields['mface']=$cfg_cmsurl."/images/noface.gif";
        }
        $fields['face'] = empty($fields['face']) ? 6 : $fields['face'];
        extract($fields, EXTR_OVERWRITE);
		if($glyhf != ''){
			$dk = "display:block";
		}else{
			$dk = "display:none";
		}
?>


<li class="comment odd alt thread-odd thread-alt depth-1">
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
    <div class="comment-author vcard">
    <a href='<?php echo $spaceurl; ?>' class='plpic' target="_blank"><img src='<?php echo $mface;?>'  height='44' width='44'/></a>
    </div>
    <div class="comment-meta">
    <span class="author"><cite><a href="<?php echo $spaceurl; ?>" target="_blank"><?php echo $username; ?></a></cite></span>
    <span class="date"> <?php echo GetDateMk($dtime); ?> </span>
     </div> 
    <div class="comment-main">
    <p><?php echo ubb($msg); ?></p>
     </div> 
     <!-- <div class="comment-floor"><?php echo $i; ?><span style="font-size:12px;">F</span></div> -->
   <ol class="children" style="<?php echo $dk; ?>"> 
   <li class="comment byuser comment-author-xiaojia bypostauthor odd alt depth-2 parent"> 
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
     <div class="comment-author vcard"> 
      <img src="<?php echo $cfg_cmsurl; ?>/images/admin_pic.jpg" class="avatar" width="44" height="44" />
     </div> 
     <div class="comment-main"> 
       
      <div class="comment-meta" style="margin-left:0;"> 
       <span class="admin-author">管理员</span> 
       <span class="author"><cite><?php echo $admin_name; ?></cite></span> 
       <span class="date"> <?php echo GetDateMk($dtime); ?> </span> 
      </div>
	  <p><?php echo $glyhf; ?></p> 
     </div> 
    </div> 
    <!-- .children --> 
   </li>
   <!-- #comment-## --> 
  </ol>
 </div>
</li>


<?php
    }
    return $totalcount;            
}

/**
 *  获取分页列表
 *
 * @param     int  $pagesize  显示条数
 * @param     int  $totalcount  总数
 * @return    string
 */
function GetPageList($pagesize, $totalcount)
{
    global $page;
    $curpage = empty($page) ? 1 : intval($page);
    $allpage = ceil($totalcount / $pagesize);
    if($allpage < 2) 
    {
        echo '';
        return ;
    }
    echo "
<div id='commetpages'>";
  echo "<span>总: {$allpage} 页/{$totalcount} 条评论</span> ";
  $listsize = 5;
  $total_list = $listsize * 2 + 1;
  $totalpage = $allpage;
  $listdd = '';
  if($curpage-1 > 0 )
  {
  echo " <a href='#commettop' onclick='LoadCommets(".($curpage-1).");'>上一页</a> ";
  }
  if($curpage >= $total_list)
  {
  $j = $curpage - $listsize;
  $total_list = $curpage + $listsize;
  if($total_list > $totalpage)
  {
  $total_list = $totalpage;
  }
  }
  else
  {
  $j = 1;
  if($total_list > $totalpage) $total_list = $totalpage;
  }
  for($j; $j <= $total_list; $j++)
  {
  echo ($j==$curpage ? "<strong>$j</strong> " : " <a href='#commettop' onclick='LoadCommets($j);'>{$j}</a> ");
  }
  if($curpage+1 <= $totalpage )
  {
  echo "<a href='#commettop' onclick='LoadCommets(".($curpage+1).");'>下一页</a> ";
  }
  echo "</div>
";
}